Imports MIMS.WRS.Business
Imports MIMS.WRS.Entities
Imports System.IO
Imports MyFramework
Imports System.Xml

Public Class IDSHDReport
    Inherits System.Web.UI.Page

    Protected WithEvents header As IDSHDReportHeader
    Protected lblErrorMsg As System.Web.UI.WebControls.Label
    Protected spanNoneReport As System.Web.UI.HtmlControls.HtmlGenericControl

    Private territory As Territory = Nothing

#Region " Web Form Designer Generated Code "

    'This call is required by the Web Form Designer.
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

    End Sub
    Protected WithEvents dlReport As System.Web.UI.WebControls.DataList

    'NOTE: The following placeholder declaration is required by the Web Form Designer.
    'Do not delete or move it.
    Private designerPlaceholderDeclaration As System.Object

    Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
        'CODEGEN: This method call is required by the Web Form Designer
        'Do not modify it using the code editor.
        InitializeComponent()
    End Sub

#End Region

    Protected Function GetTerritory() As String
        If (territory Is Nothing) Then
            territory = TerritoryService.GetTerritory(RequestContext.TerritoryID)
        End If

        If Not (territory Is Nothing) Then
            Return territory.Description
        Else
            Return ""
        End If
    End Function
    Protected Function GetPackType2Text(ByVal data As Object) As String
        If data Is DBNull.Value Then
            Return "&nbsp;"
        Else
            Return BulkOrder.GetBOPackType2Meaning(Convert.ToString(data))
        End If
    End Function

    Protected Function GetPackTypeText(ByVal data As Object) As String
        If data Is DBNull.Value Then
            Return "&nbsp;"
        Else
            Return BulkOrder.GetBOPackTypeMeaning(Convert.ToString(data))
        End If
    End Function

    Protected Function GetQtyAvailHTML(ByVal container As Object) As String
        Dim bo As BulkOrder = CType(container, BulkOrder)
        'Dim qtyAvail As Integer = bo.QuantityAvailable        
        'Dim packQty As Integer = bo.PackQty ' also is LGDCatPackQty

        'Dim isShownInLGD As Boolean = bo.IsShownInLGDCatalog

        Try
            If (bo.IDSQuantityAvail <> Nulls.NullInteger) Then
                Return bo.IDSQuantityAvail.ToString()
            Else
                Return "&nbsp;"
            End If
        Catch ex As Exception
            Return "&nspb;"
        End Try

    End Function

    Protected Function GetQtyAvailDesc(ByVal container As Object) As String
        Dim bo As BulkOrder = CType(container, BulkOrder)
        Dim qtyAvail As Integer = bo.QuantityAvailable
        Dim catPackDesc As String = bo.CatPackDesc
        Dim packQty As Integer = bo.PackQty ' also is LGDCatPackQty
        Dim unitDesc As String = bo.Pack

        Dim isShownInLGD As Boolean = bo.IsShownInLGDCatalog

        If (isShownInLGD = True) Then
            'Logger.Debug("packQty: " + packQty.ToString())
            'Logger.Debug("catPackDesc: " + catPackDesc)
            'Logger.Debug("GetPackType2Text: " + GetPackType2Text(catPackDesc))
            If packQty <> Nulls.NullInteger Then
                Return GetPackType2Text(catPackDesc)
            Else
                Return "&nbsp;"
            End If
        Else
            If qtyAvail <> Nulls.NullInteger Then
                Return GetPackTypeText(unitDesc)
            Else
                Return "&nbsp;"
            End If
        End If
    End Function

    Protected Function GetPackTypeTextNotNull(ByVal data As Object, ByVal pack As Object) As String

        If data Is DBNull.Value OrElse Convert.ToString(data).Trim.Length = 0 Then
            Return "&nbsp;"
        Else
            Dim dummy As Integer = 0
            Try
                dummy = Convert.ToInt32(data)
            Catch ex As Exception

            End Try
            If dummy = Nulls.NullInteger Then
                Return "&nbsp;"
            Else
                Return GetPackTypeText(pack)
            End If
        End If
    End Function


    Protected Function GetFOB(ByVal data As Object, ByVal unitDesc As String, ByVal obj As Object) As String
        If data Is DBNull.Value Or Convert.ToDecimal(data) = Nulls.NullDecimal Then
            Return "&nbsp;"
        Else
            Dim bo As BulkOrder = CType(obj, BulkOrder)
            If (bo.SpecialOfferDisc = Nulls.NullDecimal OrElse bo.SpecialOfferDisc = 0) Then
                Return String.Format("{0} (USD) per {1}", _
               (Convert.ToDecimal(data) * (1 - RequestContext.Discount / 100)).ToString(Config.DecimalFormat), _
               BulkOrder.GetBOPackTypeMeaning(unitDesc))
            Else
                Dim discountPercentage As Decimal
                discountPercentage = RequestContext.Discount + bo.SpecialOfferDisc
                Return String.Format("<span class='SpecialOffer'>{0} (USD) per {1}<br>SPECIAL PRICE, {2}% Discount included.</span>", _
                            (Convert.ToDecimal(data) * (1 - discountPercentage / 100)).ToString(Config.DecimalFormat), _
                            BulkOrder.GetBOPackTypeMeaning(unitDesc), discountPercentage.ToString("#######"))
            End If

        End If
    End Function

    Protected Function GetPictureHTML(ByVal data As Object) As String
        If data Is DBNull.Value Then
            Return "&nbsp;"
        Else
            Dim filePath As String = String.Format("{0}.jpg", Path.Combine(Config.ProductImagePath, Convert.ToString(data)))

            If File.Exists(filePath) Then
                Return String.Format("<img src='../ViewPicture.aspx?procode={0}&size={1}' border=0 alt='{0}.jpg'>", data, Config.BOSalesReportImageSize)
            Else
                Return "&nbsp;"
            End If
        End If
    End Function

    Protected Function GetReservedQtyText(ByVal container As Object) As String
        Dim qty As Integer = 0
        Dim pack As String = GetPackTypeText(DataBinder.Eval(container, "DataItem.Pack"))
        Try
            qty = Convert.ToInt32(DataBinder.Eval(container, "DataItem.QuantityReserved"))
        Catch ex As Exception

        End Try

        If (qty > 0) Then
            Return String.Format("{0} {1} of the quantity shown are currently under offer", qty, pack)
        Else
            Return ""
        End If

    End Function

    Protected Function GetCatalogPageHTML(ByVal container As Object) As String
        Dim catalog As Object = DataBinder.Eval(container, "DataItem.CatalogName")
        If ((Not (catalog Is DBNull.Value)) AndAlso Convert.ToString(catalog).ToUpper.StartsWith("LGD") _
            AndAlso Convert.ToString(DataBinder.Eval(container, "DataItem.Page")).Trim().Length > 0) Then
            Return String.Format("<td width='1%' nowrap>Catalogue Page:</td><td>{0}</td>", DataBinder.Eval(container, "DataItem.Page"))
        Else
            Return ""
        End If
    End Function

    Protected Function GetClearanceStockHTML(ByVal container As Object) As String
        Dim _idsSort As String = Convert.ToString(DataBinder.Eval(container, "DataItem.IDSSort"))
        If (_idsSort.Trim().ToUpper() = "CLEARANCE STOCK") Then
            Return String.Format("<br><font color='red'>{0}</font>", "Clearance Stock - Priced to Clear !")
        Else
            Return ""
        End If
    End Function

    Private Function GetSource() As BulkOrderCollection
        Return BulkOrderService.GetBulkOrdersIDSHDReport(RequestContext.ConPointID, RequestContext.CurrentUser.LOGIN_NAME, _
            Convert.ToInt32(Request.QueryString("sort")), RequestContext.Quantity, Convert.ToInt32(Request.QueryString("ownerid")), _
            RequestContext.CurrentUser.US_ID_PK, RequestContext.Target, RequestContext.TerritoryID)
    End Function

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        'If (Not IsPostBack) Then
        '    Dim cp As ConPoint = ConPointService.GetConPoint(RequestContext.ConPointID)
        '    If cp.IsDisplayed = False Then
        '        'Throw New Exception("You are not allowed to view report of this consolidation point")
        '        lblErrorMsg.Text = String.Format("You are not allowed to view report of the consolidation point - {0}.", cp.Description)
        '        header.Visible = False
        '    Else
        '        If (RequestContext.DoReport) Then
        '            Me.dlReport.DataSource = GetSource()
        '            Me.dlReport.DataBind()
        '        End If
        '    End If
        '    spanNoneReport.Visible = Not header.Visible
        'End If
        If (Not IsPostBack) Then
            If (RequestContext.DoReport) Then
                header.Visible = True
                Me.dlReport.DataSource = GetSource()
                Me.dlReport.DataBind()
            End If
            spanNoneReport.Visible = Not header.Visible
        End If
        
    End Sub

    Private Sub header_ExportPDFClick() Handles header.ExportPDFClick
        Dim source As BulkOrderCollection = GetSource()
        Dim doc As XmlDocument = RenderService.GenerateBOXML(source, Config.ProductImagePath, RequestContext.Discount, RequestContext.ShowFOB)

        Dim rootNode As XmlNode = doc.ChildNodes(0)
        Dim cp As ConPoint = ConPointService.GetConPoint(RequestContext.ConPointID)
        Dim node As XmlNode = doc.CreateElement("conpoint")
        node.AppendChild(RenderService.CreateCData(doc, cp.Description))
        rootNode.AppendChild(node)

        node = doc.CreateElement("containerloading")
        node.AppendChild(RenderService.CreateCData(doc, cp.ContainerLoading))
        rootNode.AppendChild(node)

        node = doc.CreateElement("loadingport")
        node.AppendChild(RenderService.CreateCData(doc, cp.LoadingPort))
        rootNode.AppendChild(node)

        node = doc.CreateElement("territory")
        node.AppendChild(RenderService.CreateCData(doc, GetTerritory()))
        rootNode.AppendChild(node)

        Dim boXml As String = doc.OuterXml
        Dim xslFile As String = Server.MapPath("../foxsl/foIDSHDReport.xsl")
        Dim foFile As String = Server.MapPath("../foTemp/" + String.Format("{0}{1}{2}{3}{4}{5}{6}.fo", DateTime.Now.Year, _
                DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, _
                DateTime.Now.Second, DateTime.Now.Millisecond))
        Dim pdfFile As String = String.Format("IDSHDReport_{0}{1}{2}{3}{4}{5}{6}.pdf", DateTime.Now.Year, _
                DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, _
                DateTime.Now.Second, DateTime.Now.Millisecond)
        Try
            If RenderService.GenerateFO(boXml, xslFile, foFile) Then
                Dim buffer() As Byte = RenderService.RenderFOtoPDF(foFile)
                File.Delete(foFile)

                Response.Clear()
                Response.AddHeader("Content-Disposition", String.Format("attachment;filename={0}", HttpUtility.UrlEncode(pdfFile)))
                Response.AddHeader("Content-Type", "application/pdf")
                Response.BinaryWrite(buffer)
                Response.Flush()
                Response.End()

            End If
        Catch ex As Exception
            Logger.Debug("Failed to render BO IDSHDReport PDF", ex)
        End Try
    End Sub

    Private Sub header_OKClick1(ByVal conPointID As Integer, ByVal IDSSort As Integer, ByVal quantity As Integer, ByVal discount As Decimal, ByVal showFOB As Boolean, ByVal ownerId As Integer, ByVal target As Int32, ByVal territoryId As Int32) Handles header.OKClick
        Response.Redirect(String.Format("IDSHDReport.aspx?discount={1}&showfob={2}&cpid={0}&sort={3}&qty={4}&dorpt=1&ownerid={5}&target={6}&teid={7}", _
                                conPointID, discount, Convert.ToInt32(showFOB), IDSSort, quantity, ownerId, target, territoryId))
    End Sub

    Private Sub dlReport_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataListItemEventArgs) Handles dlReport.ItemDataBound
        If (e.Item.ItemType = ListItemType.Item OrElse e.Item.ItemType = ListItemType.AlternatingItem) Then
            Dim ltrItemIndex As Literal = CType(e.Item.FindControl("ltrItemIndex"), Literal)
            ltrItemIndex.Text = (e.Item.ItemIndex + 1).ToString()
        End If
    End Sub

End Class
